package com.glwan.fixedassetapp.utils;

import android.content.Context;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {

    /**
     * 获取properties文件
     *
     * @param context
     * @param fileName
     * @return
     * @throws IOException
     */
    public static Properties getProperties(Context context, String fileName) throws IOException {
        String file = fileName + ".properties";
        Properties properties = new Properties();
        properties.load(context.openFileInput(file));
        return properties;
    }

    /**
     * 批量修改Properties
     *
     * @param context
     * @param fileName
     * @param map
     */
    public static void setPropertiesValues(Context context, String fileName, Map<String, Object> map) {
        String file = fileName + ".properties";

        Properties properties = new Properties();


        try {
            properties.load(context.openFileInput(file));
            for (Map.Entry<String, Object> item : map.entrySet()) {
                properties.setProperty(item.getKey(), String.valueOf(item.getValue()));
            }
            FileOutputStream out = context.openFileOutput(file, Context.MODE_PRIVATE);
            properties.store(out, null);
        } catch (Exception e) {
            e.printStackTrace();
            Log.i(file, "设置失败");
        }
        Log.i(file, "设置成功");
    }

    /**
     * 单独修改Properties
     *
     * @param context
     * @param fileName
     * @param key
     * @param value
     */
    public static void setPropertiesValue(Context context, String fileName, String key, String value) {
        String file = fileName + ".properties";

        Properties properties = new Properties();


        try {
            properties.load(context.openFileInput(file));
            properties.setProperty(key, value);
            FileOutputStream out = context.openFileOutput(file, Context.MODE_PRIVATE);
            properties.store(out, null);
        } catch (Exception e) {
            e.printStackTrace();
            Log.i(file, "设置失败");
        }
        Log.i(file, "设置成功");
    }

    /**
     * 删除key
     *
     * @param context
     * @param fileName
     * @param keys
     */
    public static void removePropertiesValues(Context context, String fileName, String... keys) {
        String file = fileName + ".properties";

        Properties properties = new Properties();


        try {
            properties.load(context.openFileInput(file));
            for (String key : keys) {
                properties.remove(key);
            }
            FileOutputStream out = context.openFileOutput(file, Context.MODE_PRIVATE);
            properties.store(out, null);
        } catch (Exception e) {
            e.printStackTrace();
            Log.i(file, "设置失败");
        }
        Log.i(file, "设置成功");
    }


}
